package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static final Long expire = 1000 * 60 * 60l;
    private static final SecretKey secretKey = Keys.hmacShaKeyFor("dbd978ccdbbe8b6de77f6b37b5df9b5b62a7e892a501c3b53eaa16b0838bd5ed".getBytes());
    /*
        创建token
    token: 包含三部分: 头,负载,签名
        负载: 在token中保存的登录用户的相关信息(userName账号,userId唯一标识)
        eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ
        .H4sIAAAAAAAA_6tWKi5NUrJSyslPz8zTLcnPTs1T0lFKrShQsjI0N7Y0MjcxNrXUUSotTi3yTAGKQZh-ibmpQE2JKbmZeUq1ADNmvgxEAAAA
        .M2XoOuULJzrfMDnmgXi671qqOumnKutML-HaMUCkrtHpcx21CUllJfGIc00oYZoWwE5DJitacIxP4hI1-GWaCw

    */
    public static String createToken(String userName, Long userId) {

        String token = Jwts.builder()
                .setSubject("login-token") //token中的主题
                .setExpiration(new Date(System.currentTimeMillis() + expire)) //token的过期时间
                .claim("userId", userId)    //登录用户的唯一标识id
                .claim("userName", userName) //登录用户的账号
                .signWith(secretKey) //签名
                .compressWith(CompressionCodecs.GZIP) //对token进行压缩: 减少带宽的占用
                .compact();  //生成token

        return token;
    }

    //解析token

    public static Claims parseToken(String token) {
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return claimsJws.getBody();
    }

    public static void main(String[] args) {
        String token = createToken("admin", 1l);
        System.out.println(token);

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Claims claims = parseToken(token);
        System.out.println(claims);
    }
}
